package com.wnhz.work.yz.activity;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.ProjectOrder2Adapter;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.BudgetPayListBean;
import com.wnhz.work.yz.bean.ProjectChildBean;
import com.wnhz.work.yz.bean.ProjectDetailsBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.NoScrollListView;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ---项目详情
 */
public class ProjectDetailsActivity extends BaseActivity implements View.OnClickListener {
    private TextView title;
    private NoScrollListView my_listView;
    private ProjectOrder2Adapter mAdapter;
    private TextView tv_project_code;
    private String budget_id;

    private TextView tv_name;
    private TextView tv_phone;
    private TextView tv_address;
    private TextView tv_order_time;
    private TextView tv_pay_type;
    private TextView tv_pact_type;
    private TextView tv_message;
    private TextView tv_car;
    private TextView tv_send;
    private TextView tv_remark;
    private TextView tv_goods_price;
    private TextView rl_bottom;
    private List<ProjectChildBean> dataList = new ArrayList<>();
    private TextView tv_text99;
    private TextView goto_pay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_details);

        initData();
        initView();
    }

    private String name = "";
    private String can_pay = "";

    private void initData() {
        Bundle bundle = getIntent().getExtras();
        budget_id = getIntent().getStringExtra("budget_id");
        name = getIntent().getStringExtra("tv_project_code");
        can_pay = getIntent().getStringExtra("canPay");
        Log.e("asdsad", bundle.getString("canPay") + "+" + name + "+" + budget_id);
    }

    private void initView() {
        tv_text99 = (TextView) findViewById(R.id.tv_text99);
        tv_text99.setOnClickListener(this);
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("项目详情");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        tv_project_code = (TextView) findViewById(R.id.tv_project_code);
        goto_pay = (TextView) findViewById(R.id.goto_pay);
        goto_pay.setOnClickListener(this);
        tv_project_code.setText(name + "");
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_order_time = (TextView) findViewById(R.id.tv_order_time);
        tv_pay_type = (TextView) findViewById(R.id.tv_pay_type);
        tv_pact_type = (TextView) findViewById(R.id.tv_pact_type);
        tv_message = (TextView) findViewById(R.id.tv_message);
        tv_car = (TextView) findViewById(R.id.tv_car);
        tv_send = (TextView) findViewById(R.id.tv_send);
        tv_remark = (TextView) findViewById(R.id.tv_remark);
        tv_goods_price = (TextView) findViewById(R.id.tv_goods_price);
//        rl_bottom = (TextView) findViewById(R.id.rl_bottom);
//        rl_bottom.setOnClickListener(this);
        my_listView = (NoScrollListView) findViewById(R.id.my_listView);

        findViewById(R.id.max_buttom).setVisibility(View.GONE);
        upload();
    }

    private static final String TAG = "ProjectDetailsActivity";
    ProjectDetailsBean bean = new ProjectDetailsBean();

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("budget_id", budget_id);
        XUtil.Post(Url.BUDGET_GETBUDGETDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:TDETAIL= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");

                    Gson gson = new Gson();
                    bean = gson.fromJson(jsonObject.optString("info"), ProjectDetailsBean.class);

                    tv_name.setText(bean.getConsignee());
                    tv_phone.setText(bean.getMobile());
                    tv_address.setText(bean.getProvince() + bean.getCity() + bean.getDistrict() + bean.getAddress());
                    tv_order_time.setText(bean.getDeliver_time());
                    switch (Integer.parseInt(bean.getPay_way())) {
                        case 1:
                            tv_pay_type.setText("一次付清");
                            break;
                        case 2:
                            tv_pay_type.setText("两次付清");
                            break;
                        case 3:
                            tv_pay_type.setText("三次付清");
                            break;
                    }
                    tv_pact_type.setText(bean.getContract());
                    if ("0".equals(bean.getReceipt_data().getResult())) {
                        tv_message.setText("暂无发票信息");
                    } else {
                        tv_message.setText("" + bean.getReceipt_data().getInvoice_type());
                    }

                    tv_goods_price.setText("¥ " + bean.getTotal_fee());
                    tv_car.setText(bean.getVehicle_requir());
                    tv_send.setText(bean.getDeliver_requir());
                    tv_car.setText(bean.getVehicle_requir());
                    tv_send.setText(bean.getDeliver_requir());
                    tv_remark.setText(bean.getMessage());
                    List<ProjectDetailsBean.GoodsDataEntity> list = bean.getGoods_data();
                    for (int i = 0; i < list.size(); i++) {
                        ProjectChildBean c = new ProjectChildBean();
                        c.setRoom_number(list.get(i).getRoom_number());
                        c.setPackage_cate(list.get(i).getPackage_cate());
                        c.setGoods_pic(list.get(i).getGoods_pic());
                        c.setSku_info(list.get(i).getSku_info());
                        c.setColor(list.get(i).getColor());
                        c.setPackage_id(list.get(i).getPackage_id() + "");
                        c.setNums(list.get(i).getNums());
                        c.setPrice(list.get(i).getPrice());
                        c.setGoods_name(list.get(i).getGoods_name());
                        dataList.add(c);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //   mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mAdapter = new ProjectOrder2Adapter(ProjectDetailsActivity.this, dataList);
                my_listView.setAdapter(mAdapter);

                my_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(ProjectDetailsActivity.this, ProjectListActivity.class);
                        intent.putExtra("budget_id", budget_id);
                        intent.putExtra("package_id", dataList.get(position).getPackage_id());
                        intent.putExtra("goods_name", dataList.get(position).getGoods_name() + "");
                        Log.e("----", budget_id + "--" + dataList.get(position).getPackage_id() + "--" + dataList.get(position).getGoods_name());

                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.goto_pay:
                upLoadPay(budget_id);
                break;
            case R.id.tv_text99:
                startActivity(new Intent(this, ProjectProgressActivity.class).putExtra("budget_id", budget_id));
                break;
            default:
                break;
        }
    }

    private BudgetPayListBean.InfoEntity info;

    private void upLoadPay(final String budget_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("budget_id", budget_id);
        XUtil.Post(Url.BUDGET_GETBUDGETPAYLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("budget_id", result + "");
                Gson g = new Gson();
                BudgetPayListBean budgetPayListBean = g.fromJson(result, BudgetPayListBean.class);
                info = budgetPayListBean.getInfo();
//                if (info.getPay_way().equals(info.getPay_list().size() + "")) {
//                    goto_pay.setVisibility(View.GONE);
//                }
            }

            @Override
            public void onFinished() {
                setGotoPay(budget_id);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private List<String> imgUrl = new ArrayList<>();
    private ImageView add_img;

    private void setGotoPay(final String budget_id) {
        imgUrl.clear();
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.dialog_pay, null);

        TextView need_pay = (TextView) view.findViewById(R.id.need_pay);
        final EditText me_pay_money = (EditText) view.findViewById(R.id.me_pay_money);
        need_pay.setText("￥" + info.getNeed_pay_money());

        LinearLayout ll_pay = (LinearLayout) view.findViewById(R.id.ll_pay);
        ll_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);
                im.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                me_pay_money.setSelected(true);
                me_pay_money.setClickable(true);
                me_pay_money.setFocusable(true);
                me_pay_money.setFocusableInTouchMode(true);
            }
        });
        TextView submit = (TextView) view.findViewById(R.id.submit);
        RecyclerView recycler = (RecyclerView) view.findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        RecyclerView tianjia = (RecyclerView) view.findViewById(R.id.tianjia);
        tianjia.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        add_img = (ImageView) view.findViewById(R.id.add_img);
        add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopmenu(v);
            }
        });

        final List<String> a = info.getPay_list();
        recycler.setAdapter(new BaseRVAdapter(this, a) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.dialog_recycler_project;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                holder.setTextView(R.id.pay_msg, a.get(position));
            }
        });


        adapter2 = new Myadapter2(this, imgUrl);
        tianjia.setAdapter(adapter2);
        builder.setView(view);
        final AlertDialog show = builder.show();
        if (info.getNeed_pay_money().equals("0")) {
            show.dismiss();
        }
        Window dialogWindow = show.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        lp.height = MyApplication.getInstance().window_h * 2 / 3; // 高度
        dialogWindow.setAttributes(lp);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upLoadGoToPay(budget_id, me_pay_money.getText().toString());
                showDialog();
                show.dismiss();
            }
        });
    }

    private void upLoadGoToPay(String budget_id, String need_pay_money) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("budget_id", budget_id);
        map.put("need_pay_money", need_pay_money);


        for (int i = 0; i < imgUrl.size(); i++) {
            String targetPath = imgUrl.get(i);
            //调用压缩图片的方法，返回压缩后的图片path
            String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
            File compressedPic = new File(compressImage);
            map.put("pic" + i, compressedPic);
            Log.e("-----", compressedPic + "----" + compressImage);
        }
        XUtil.Post(Url.BUDGET_UPLOADBUDGETPAYRECORD, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("need_pay_money", result + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                //notifyDataSetChanged();
                //  AllProjectAdapter.this.notifyDataSetChanged();
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    private Myadapter2 adapter2;

    class Myadapter2 extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public Myadapter2(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.dialog_add_tupian;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            x.image().bind(holder.getImageView(R.id.add_tu), imgUrl.get(position));
            holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialogv7("确定删除吗？", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            imgUrl.remove(position);
                            adapter2.notifyDataSetChanged();
                            add_img.setVisibility(View.VISIBLE);
                        }
                    });
                }
            });
        }
    }

    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    public void showPopmenu(View v) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

//        // 显示窗口位置
        menuWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private String imageName = "";
    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;


        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    System.out.println("=====1234=====");
                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";

                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    System.out.println("拍照的路径---" + imageName);
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    String imagePath = AlbumImagePath.getPath(this, uri);
                    System.out.println("imagePath**====www==" + imagePath);

//                    if (!compressFile.exists()) {
//                        compressFile = new File(FilesPath);
//                        compressFile.mkdirs();
//                    }
//                    String targetPath = compressFile.getAbsolutePath() +df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//                    updateImage(compressImage, uri, currentClick);
                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    File tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

//                    if (!compressFile.exists()) {
//                        compressFile = new File(FilesPath);
//                        compressFile.mkdirs();
//                    }
                    File file = new File(imagePath);
//                    Log.i(TAG, "onActivityResult: 拍照图片是否存在===" + file.exists());

                    if (!file.exists()) {
                        return;
                    }

//                    String targetPath = compressFile.getAbsolutePath() + df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//
//                    updateImage(compressImage, uri, currentClick);
                    updateImage(imagePath, uri);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;

        }
    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }

        System.out.println("===修改的imagePath===" + imagePath);
//        ImageLoader.getInstance().displayImage("file://" + imagePath, iv_edit_head);
        if (imgUrl.size() < 4) {
            imgUrl.add(imagePath);
            adapter2.notifyDataSetChanged();
        }
        if (imgUrl.size() >= 4) {
            add_img.setVisibility(View.GONE);
        } else {
            add_img.setVisibility(View.VISIBLE);
        }

    }
}
